<script setup>
import { reactive, ref, onMounted} from 'vue';
import { ElMessage } from 'element-plus';
import MapSelector from '../common/MapSelector.vue';
import { userStatusMap} from '@/utils/dict';
import { useRouter } from 'vue-router';
import { updateEmployee,createEmployee,queryEmPageList,deleteEmployee } from '@/apis/employeeAPI';
import {queryPageList} from '@/apis/userAPI';
const router=useRouter();
const userList = ref([]);
const fetchUserData=async()=>{
  try{
    params.value.pageNo=1;
    params.value.pageSize=1000;
    params.value.type=0;
    const { data } = await queryPageList(params.value);
    const { records } = data;
    userList.value=records;
    console.log("后端返回的数据",records);
    total.value=data.total;
  }catch{
    ElMessage.error("加载失败");
  }
}
// 1. 表格数据源必须是数组（每个元素对应一行）
const employeeList = ref([]);
// 搜索方法
const handleSearch = () => {
  params.value.pageNo=1;
  fetchData();
}
// 2. 编辑对话框相关状态
const isEditDialogOpen = ref(false); // 控制对话框显示/隐藏
const currentEmployee = reactive({
  id:'',
  monthOrderCount:'',
  currentOrderCount:'',
  starLevel:'',
  level:'',
  tags:'',
  status:'',
  currentLocation:''
});
const addressInfo = ref({
  address: '',
  longitude: '',
  latitude: ''
});
const employeeForm = reactive({
  id:'',
  userId:'',
  monthOrderCount:'',
  currentOrderCount:'',
  starLevel:'',
  level:'',
  tags:'',
  status:'',
  currentLocation:''
});
// 3. 页面加载时填充数据（模拟接口请求）
onMounted(async () => {
  await fetchData();
});



// 分页相关变量

const currentPage = ref(1);      // 当前页码
const pageSize = ref(10);         // 每页条数

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;  // 重置为第一页
  fetchData();
};

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};


// 编辑功能
const openDialog = (employee) => {
  Object.keys(currentEmployee).forEach(k => delete currentEmployee[k])
  Object.assign(currentEmployee,employee);
  isEditDialogOpen.value = true;
};

//  保存编辑
const saveEmployee = async() => {
  try{
    console.log("完整的编辑数据",currentEmployee)
    await updateEmployee(currentEmployee);
    ElMessage.success("编辑成功");
    fetchData();
  }catch{
    ElMessage.error("编辑失败");

  }finally{
    isEditDialogOpen.value=false;

  }
};
const isAddDialogOpen=ref(false);
const isAddOpen=()=>{
  isAddDialogOpen.value=true;
  fetchUserData();
}
// 6. 删除功能
const deleteEm= async(employee) => {
 const deleteId = employee.id;
  try {
    await deleteEmployee(deleteId);
    // 后端删除成功后，删除本地列表中的对应数据
    const index = employeeList.value.findIndex(item => item.id === deleteId);
    fetchData();
    if (index !== -1) {
    employeeList.value.splice(index, 1);
    }
    ElMessage.success('删除成功');
    fetchData();
  } catch {
    ElMessage.error("删除失败");
  }
};
const toDetail=(row)=>{
   router.push({
    path: `/userInfoDetail/${row.id}`, // 动态路由路径
  });
};
//添加
const addEmployee=async(employeeForm)=>{
  try{
    employeeForm.currentLocation=addressInfo.value.address;
    await createEmployee(employeeForm);
    console.log("完整的添加数据",employeeForm)
    ElMessage.success("添加成功");
    fetchData();
  }catch{
    ElMessage.error("添加失败");
  }finally{
    isAddDialogOpen.value=false;
  }

}
const total=ref(0);
const params=ref({
  pageNo:'',
  pageSize:'',
  startDate:'',
  status:'',
  type:''
}
)
const fetchData=async()=>{
  try{
    params.value.pageNo=currentPage.value;
    params.value.pageSize=pageSize.value;
    const { data } = await queryEmPageList(params.value);
    const { records } = data;
    employeeList.value=records;
    console.log("后端返回的数据",records);
    total.value=data.total;
    // ElMessage.success("加载成功");
  }catch{
    ElMessage.error("加载失败");
  }
}
</script>
<template>
  <div class="container">
    <div class="employeeList-header">
     <div class="search-box">
        <el-select v-model="params.status" placeholder="状态" style="margin-left: 10px; width: 150px;" clearable >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
         <el-date-picker  v-model="params.startDate" type="date"  placeholder=" 创建时间"  style="margin-left: 10px; width: 150px;"  value-format="YYYY-MM-DDTHH:mm:ss.000Z"/>
        <el-button type="primary" @click="handleSearch" style="margin-left: 10px;"> 搜索</el-button>
        <el-button class="addBtn" type="primary" @click="isAddOpen">添加</el-button>
     </div>
    </div>
    <!-- 表格必须绑定数组数据 -->
    <div class="table_container">
    <el-table :data="employeeList"  border style="width: 900px; margin-top: 20px; min-height:100%;">
      <el-table-column label="ID" prop="id" min-width="80%" width="80%">
      </el-table-column>
      <el-table-column label="月工单" prop="monthOrderCount" min-width="50%" />
      <el-table-column label="进行中" prop="currentOrderCount" min-width="50%" />
      <el-table-column label="星级" min-width="150" width="150">
        <template #default="scope">
          <el-rate v-model="scope.row.starLevel" text-color="#ff9900" score-template="{value}" disabled/>
        </template>
      </el-table-column>
      <el-table-column label="等级" prop="level"  min-width="80%" width="80%" > </el-table-column>
      <el-table-column label="标签" prop="tags"  min-width="100%" >
        <template #default="scope">
          <el-tag type="success">{{ scope.row.tags }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status"  min-width="80%"  type="number">
        <template #default="scope">
          <el-tag type="priamry" v-if="scope.row.status === 1">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
          <el-tag type="error" v-if="scope.row.status === 0">{{ userStatusMap[scope.row.status] ?? '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作"  min-width="100%">
        <template #default="scope">  <!-- 必须用template包裹按钮 -->
          <div class="btn">
            <el-button @click="openDialog(scope.row)">编辑</el-button>
            <el-button type="danger" @click="deleteEm(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="margin-top: 15px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        page-sizes=10
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    </div>

    <!-- 编辑对话框 -->
    <el-dialog v-model="isEditDialogOpen" title="编辑" width="700px">
      <el-form :model="currentEmployee" style="width: 500px" label-width="80px">
        <el-form-item label="等级" >
          <el-select v-model="currentEmployee.level" placeholder="请选择等级">
            <el-option label="金牌" value="金牌"/>
            <el-option label="银牌" value="银牌"/>
            <el-option label="铜牌" value="铜牌"/>
            <el-option label="普通" value="普通"/>
          </el-select>
        </el-form-item>
        <el-form-item label="标签" label-width="80px">
          <el-input v-model="currentEmployee.tags" type="text"></el-input>
        </el-form-item>
        <el-form-item label="当前位置" label-width="80px">
      <!-- 导入地图选点组件 -->
          <MapSelector v-model="currentEmployee.currentLocation">
        <!-- 通过插槽传入地址输入框 -->
            <template #address-input>
              <el-input v-model="currentEmployee.currentLocation" />
            </template>
          </MapSelector>
          </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="currentEmployee.status" label-width="80px">
            <el-option label="禁用" :value="0"/>
            <el-option label="启用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogOpen = false">取消</el-button>
        <el-button type="primary" @click="saveEmployee">保存</el-button>
      </template>
    </el-dialog>
    <!-- 创建 -->
    <el-dialog v-model="isAddDialogOpen" title="添加">
      <el-form :model="employeeForm" label-width="100px" style="width: 400px">
        <el-form-item label="等级">
          <el-select v-model="employeeForm.level" placeholder="请选择等级">
            <el-option label="金牌" value="金牌"/>
            <el-option label="银牌" value="银牌"/>
            <el-option label="铜牌" value="铜牌"/>
            <el-option label="普通" value="普通"/>
          </el-select>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="employeeForm.tags" type="text"></el-input>
        </el-form-item>
        <el-form-item label="用户">
          <el-select v-model="employeeForm.userId" clearable @change="userChange" placeholder="请选择用户">
            <el-option v-for="u in userList" :key="u.id" :label="u.customerName" :value="u.id">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="当前位置">
          <MapSelector v-model="addressInfo.address">
        <!-- 通过插槽传入地址输入框 -->
            <template #address-input>
              <el-input v-model="addressInfo.address" placeholder="请输入地址或通过地图选择"/>
            </template>
          </MapSelector>
        </el-form-item>

      </el-form>
      <template #footer>
        <el-button @click="isAddOpen = false">取消</el-button>
        <el-button type="primary" @click="addEmployee(employeeForm)">保存</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<style scoped lang="scss">
.container {
  padding: 20px;
  background-color: white;
  min-height: 100vh; /* 使用100vh确保占满视口高度，100%可能因父元素高度问题无效 */
  width: 100%;
  display: flex; /* 开启Flex布局 */
  flex-direction: column; /* 子元素垂直排列 */
  align-items: center; /* 水平居中 */
  justify-content: flex-start; /* 垂直从顶部开始排列，可根据需要调整 */
}
.employeeList-header {
  display: flex;
  justify-content: space-between; /* 左右两端对齐 */
  align-items: center; /* 垂直居中对齐 */
  padding-left: 15px;
  padding-right: 15px; /* 右侧留与左侧相同的间距 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
  margin-bottom: 15px; /* 与下方表格保持距离 */
}
.search-box {
  padding-left: 15px;
  display: flex; /* 使用Flex布局使输入框和按钮横向排列 */
  align-items: center; /* 垂直居中对齐 */
  width: calc(100% - 30px);
  margin: 0 auto;
  box-sizing: border-box;
}
.btn{
  display: flex;
  gap: 2px;
}
.pagination-container {
  // padding: 10px 0;
  align-items: center;
}

/* 表格容器 */
.table_container {
  background-color: white;
  height: 300px;
  width: calc(100% - 30px); /* 宽度与搜索框一致 */
  margin-left: 35px; /* 左侧外边距15px，与搜索框padding-left匹配 */
  margin-top: 40px;
  box-sizing: border-box; /* 避免边框/内边距影响宽度 */

}
.title-link {
  color: #409eff; /* 蓝色，模拟链接样式 */
  cursor: pointer;
  text-decoration: underline; /* 下划线，增强可点击提示 */
}

</style>
